package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.table.*;
import javax.swing.text.TableView.TableRow;


import view.EmployeesPanel.TableModel;

import model.Messages;
import net.miginfocom.swing.MigLayout;

public class MessagePanel extends JPanel {
	private static final long serialVersionUID = 1L;

	//JTable Header
	private String[] headers = {"Message", "Sender", "Date", "Department", " "};
	private String[] sendHeaders = {"Inbox","Spam", "Old Messages", "Trash"};
	
	//Keep track of where we are moving the message to
	private String sendingTo;
	private int row;
	
	//Tabbed Pane
	private JTabbedPane tabbedPane;
	
	//Our message data
	private Messages message;
	
	//Components
	private JButton delete;
	private JButton compose;
	private JButton move;
	private JComboBox sendTo;
	private JTextArea mess;
	private JTextField senderName;
	private JTextField title;
	private JTextField department;
	private JTable target;
	
	//JDialog
	JDialog Dialog;
	
	/**
	 * Class constructor.
	 */
	public MessagePanel()
	{
		message = new Messages();

		//Set this components Layout
		this.setLayout(new MigLayout("fillx,insets 25"));
		
		//Set Layout Size
		Toolkit tk = Toolkit.getDefaultToolkit();		
		this.setMaximumSize(new Dimension(tk.getScreenSize()));
		this.setBackground(Color.WHITE);
		
		//Initialize Components
		try {
			init();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}
	
	/**
	 * initialize components
	 * @throws IOException
	 */
	public void init() throws IOException
	{
		//Create Buttons
		delete = new JButton("Delete");
		compose = new JButton("Compose");
		move = new JButton("Move");
		sendTo = new JComboBox(sendHeaders);
		
		//Register Action Listeners and ItemListeners
		delete.addActionListener(new delete());
		compose.addActionListener(new compose());
		move.addActionListener(new move());
		sendTo.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent ie){				
				sendingTo  = (String)sendTo.getSelectedItem();
		}
		});
		
		//Create TabbedPane
		tabbedPane = new JTabbedPane();
		
		//Add our Tabs
		JPanel inbox = makePane(new inboxModel());		
		tabbedPane.addTab("Inbox", inbox);

		JComponent spam = makePane(new spamModel());
		tabbedPane.addTab("Spam", spam);
		
		JComponent inboxdata = makePane(new oldmsgModel());
		tabbedPane.addTab("Old Messages", inboxdata);
		
		JComponent trash = makePane(new trashModel());		
		tabbedPane.addTab("Trash", trash);					
		this.add(tabbedPane);
		this.add(compose, "cell 0 1");
		this.add(delete, "cell 0 1, gap 20");
		this.add(move, "cell 0 1, gap 20");
		this.add(sendTo, "cell 0 1");
	}
	/**
	 * Opens up a Dialog Window
	 */
	public void sendWindow(String type, int row)
	{
		//Create new JDialog
		Dialog = new JDialog();
		
		//Set it to middle of screen
		Toolkit tk = Toolkit.getDefaultToolkit();
		Dimension screenSize = tk.getScreenSize();
		Dialog.setLocation((screenSize.width - Dialog.getWidth())/3, (screenSize.height-Dialog.getHeight())/3);
		Dialog.setResizable(false);
		
		//Set the Layout
		MigLayout migLayout = new MigLayout("", "[right]");
		Dialog.setLayout(migLayout);
		
		//Create dialog Component			
		senderName = new JTextField(25);
		department = new JTextField(25);
		title = new JTextField(25);
		mess = new JTextArea(10, 20);
		JButton send = new JButton("Send");
		JButton cancel = new JButton("Cancel");		
		JButton Reply = new JButton("Reply");
		
		//set actionlisteners
		cancel.addActionListener(new Cancel());
		
		//Add Components
		if(type.compareTo("Reply")==0)
		{
			//set actionlisteners
			Reply.addActionListener(new sent());
			
			//set the text
			mess.setText(target.getValueAt(row, 0).toString());
			senderName.setText(target.getValueAt(row, 1).toString());
			department.setText(target.getValueAt(row, 3).toString());
				
			//Add Components
			Dialog.add(new JLabel("To : "), "align left");
			Dialog.add(senderName, "span, growx");
			Dialog.add(new JLabel("Department : "), "align left");
			Dialog.add(department, "span, growx");
			Dialog.add(new JLabel("Message"), "align left");
			Dialog.add(mess, "span, growx");
			Dialog.add(Reply, "gap 50, align left, gaptop 30");
			Dialog.add(cancel, "gapright 50");
			Dialog.setTitle("Read Message");
		}else
		{
			//set actionlisteners
			send.addActionListener(new sent());
			
			Dialog.add(new JLabel("To : "), "align left");
			Dialog.add(senderName, "span, growx");
			Dialog.add(new JLabel("Department : "), "align left");
			Dialog.add(department, "span, growx");
			Dialog.add(new JLabel("Title : "), "align left");
			Dialog.add(title, "span, growx");
			Dialog.add(new JLabel("Message : "), "align left");
			Dialog.add(mess, "span, growx");
			Dialog.add(send, "gap 50, align left, gaptop 30");
			Dialog.add(cancel, "gapright 50");
			Dialog.setTitle("Compose Message");
		}
		
		
		//Set visible
		Dialog.pack();
		Dialog.setModal(true);
		Dialog.setVisible(true);
		
	}
	
	/**
	 * Creates our JPanel
	 * @return
	 */
	public JPanel makePane(AbstractTableModel as)
	{
		JPanel panel = new JPanel(new MigLayout("fillx,insets 25"));
		//create table
	    JTable table = new JTable(as);
	    
	    //Get MousListener
	    table.addMouseListener(new MouseClick());
	    
	    //Set our JTable size
		table.setPreferredScrollableViewportSize(new Dimension(this.getMaximumSize().width - 100, this.getMaximumSize().height - 300));
		table.setFillsViewportHeight(true);
		
		//Add to panel
		panel.add(new JScrollPane(table));
		return panel;
	}	
	/**
	 * inbox table model
	 * @author shin
	 *
	 */
	class inboxModel extends AbstractTableModel {
	
		public int getColumnCount() {
			return headers.length;
		}

		public int getRowCount() {
			return message.getMessages().size();
		}

		public String getColumnName(int col) {
			return headers[col];
		}

		public Object getValueAt(int row, int col) {			
			return message.getMessages().get(row)[col];
		}

		public boolean isCellEditable(int row, int col) {
			 if (col == 4) { 
	                return true; 
	        } else 
	                return false; 
	
		}
		public Class getColumnClass(int c) {
	           return getValueAt(0, c).getClass();
	    }
		 public void setValueAt(Object value, int row, int col) {
			 message.getMessages().get(row)[col] = value;
	            fireTableCellUpdated(row, col);
	        }
	}
	/**
	 * inbox table model
	 * @author shin
	 *
	 */
	class spamModel extends AbstractTableModel {
	
		public int getColumnCount() {
			return headers.length;
		}

		public int getRowCount() {
			return message.getSpam().size();
		}

		public String getColumnName(int col) {
			return headers[col];
		}

		public Object getValueAt(int row, int col) {			
			return message.getSpam().get(row)[col];
		}

		public boolean isCellEditable(int row, int col) {
			 if (col == 4) { 
	                return true; 
	        } else 
	                return false; 
	
		}
		public Class getColumnClass(int c) {
	           return getValueAt(0, c).getClass();
	    }
		 public void setValueAt(Object value, int row, int col) {
			 message.getSpam().get(row)[col] = value;
	            fireTableCellUpdated(row, col);
	        }
	}
	/**
	 * inbox table model
	 * @author shin
	 *
	 */
	class oldmsgModel extends AbstractTableModel {
	
		public int getColumnCount() {
			return headers.length;
		}

		public int getRowCount() {
			return message.getOldMessage().size();
		}

		public String getColumnName(int col) {
			return headers[col];
		}

		public Object getValueAt(int row, int col) {			
			return message.getOldMessage().get(row)[col];
		}

		public boolean isCellEditable(int row, int col) {
			 if (col == 4) { 
	                return true; 
	        } else 
	                return false; 
	
		}
		public Class getColumnClass(int c) {
	           return getValueAt(0, c).getClass();
	    }
		 public void setValueAt(Object value, int row, int col) {
			 message.getOldMessage().get(row)[col] = value;
	            fireTableCellUpdated(row, col);
	        }
	}
	/**
	 * trash table model
	 * @author shin
	 *
	 */
	class trashModel extends AbstractTableModel {
	
		public int getColumnCount() {
			return headers.length;
		}

		public int getRowCount() {
			return message.getTrash().size();
		}

		public String getColumnName(int col) {
			return headers[col];
		}

		public Object getValueAt(int row, int col) {			
			return message.getTrash().get(row)[col];
		}

		public boolean isCellEditable(int row, int col) {
			 if (col == 4) { 
	                return true; 
	        } else 
	                return false; 
	
		}
		public Class getColumnClass(int c) {
	           return getValueAt(0, c).getClass();
	    }
		 public void setValueAt(Object value, int row, int col) {
			 message.getTrash().get(row)[col] = value;
	            fireTableCellUpdated(row, col);
	        }
	}
	/**
	 * Moves to trash, if we are in trash tab will delete
	 * @author shin
	 *
	 */
	class delete implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{
			//Confirm if the user wants to delete
			boolean deletedata = true;
			
			//If the user clicks yes
			int ans=7777;
			
			//Gets our current JTab
			int tab = tabbedPane.getSelectedIndex();			
			//If we are in the Inbox Tab
			if(tab==0)
			{
				for(int row=0;row<message.getMessages().size();row++)
				{
					if(message.getMessages().get(row)[4].equals(true))
					{
						if(deletedata){					
							ans = JOptionPane.showConfirmDialog(MessagePanel.this, "Are you sure you want to delete this Messages?","Delete?",JOptionPane.YES_NO_OPTION);
							deletedata=false;
						}		
						if(ans == JOptionPane.YES_OPTION){
							message.sendTo(message.getMessages(), message.getTrash(), row);							
							row--;
						}
						if(ans == JOptionPane.NO_OPTION)
							break;
					}					
				}
			}else
			{	//If we are in the Spam tab				
				if(tab==1)
				{
					for(int row=0;row<message.getSpam().size();row++)
					{
						if(message.getSpam().get(row)[4].equals(true))
						{
							if(deletedata){					
								ans = JOptionPane.showConfirmDialog(MessagePanel.this, "Are you sure you want to delete this Messages?","Delete?",JOptionPane.YES_NO_OPTION);
								deletedata=false;
							}		
							if(ans == JOptionPane.YES_OPTION){
								message.sendTo(message.getSpam(), message.getTrash(), row);								
								row--;
							}
							if(ans == JOptionPane.NO_OPTION)
								break;
						}					
					}
				}else
				{	//If we are in the Old Message Tab
					if(tab==2)
					{
						for(int row=0;row<message.getOldMessage().size();row++)
						{
							if(message.getOldMessage().get(row)[4].equals(true))
							{
								if(deletedata){					
									ans = JOptionPane.showConfirmDialog(MessagePanel.this, "Are you sure you want to delete this Messages?","Delete?",JOptionPane.YES_NO_OPTION);
									deletedata=false;
								}		
								if(ans == JOptionPane.YES_OPTION){
									message.sendTo(message.getOldMessage(), message.getTrash(), row);								
									row--;
								}
								if(ans == JOptionPane.NO_OPTION)
									break;
							}					
						}
					}else
					{	//If we are in the trash tab
						if(tab==3)
						{
							for(int row=0;row<message.getTrash().size();row++)
							{
								if(message.getTrash().get(row)[4].equals(true))
								{
									if(deletedata){					
										ans = JOptionPane.showConfirmDialog(MessagePanel.this, "Are you sure you want to delete this Messages?","Delete?",JOptionPane.YES_NO_OPTION);
										deletedata=false;
									}		
									if(ans == JOptionPane.YES_OPTION){
										message.getTrash().remove(row);							
										row--;
									}
									if(ans == JOptionPane.NO_OPTION)
										break;
								}					
							}
						}
					}
				}
			}
		
			repaint();
		}
	}
	/**
	 * Compose a message
	 * @author shin
	 *
	 */
	class compose implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{
			sendWindow("Send",0);	
		}
	}

	/**
	 * Move data to another tab
	 * @author shin
	 *
	 */
	class move implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{	
			int tab = tabbedPane.getSelectedIndex();
			Vector<Object[]> currentTabObject = null;
			
			if(tab==0) currentTabObject = message.getMessages();
			else if(tab==1) currentTabObject = message.getSpam();
			else if(tab==2) currentTabObject = message.getOldMessage();
			else currentTabObject = message.getTrash();
			
			for(int row=0;row<currentTabObject.size();row++)
			{
				if(currentTabObject.get(row)[4].equals(true))
				{	
					if(sendingTo.compareTo("Inbox")==0) message.sendTo(currentTabObject, message.getMessages(), row);
					else if(sendingTo.compareTo("Spam")==0) message.sendTo(currentTabObject, message.getSpam(), row);	
					else if(sendingTo.compareTo("Old Messages")==0) message.sendTo(currentTabObject, message.getOldMessage(), row);	
					else message.sendTo(currentTabObject, message.getTrash(), row);						
					row--;
				}
			}				
			repaint();
		}
	}
	/**
	 * Cancel JDialog
	 * @author shin
	 *
	 */
	class Cancel implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{
			Dialog.setVisible(false);
		}
	}
	/**
	 * Sends the message
	 * @author shin
	 *
	 */
	class sent implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{	
			//Get the Action
			String action = e.getActionCommand();
			
			//Set the Date
			DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
			Date dates = new Date();
			if(senderName.getText().compareTo("")!=0 && mess.getText().compareTo("")!=0 && department.getText().compareTo("")!=0)
			{
				if(action.compareTo("Reply")==0){
					message.addMessages(mess.getText(), senderName.getText(), dateFormat.format(dates), department.getText());			
				}			
				if(action.compareTo("Send")==0){
					message.addMessages(mess.getText(), senderName.getText(), dateFormat.format(dates), department.getText());
					
				}				
				Dialog.setVisible(false);
				JOptionPane.showMessageDialog(null, "Message Sent");
				repaint();
			}else
			{
				JOptionPane.showMessageDialog(null, "One or more Fields are empty");
			}
			
		}
	}
	/**
	 * 
	 */
	class MouseClick implements MouseListener
	{   

		@Override
		public void mouseClicked(MouseEvent e) {
			if (e.getClickCount() == 2) {        
				target = (JTable)e.getSource();         
	    		row = target.getSelectedRow();
				sendWindow("Reply", row);
	    		
	    	} 
			
		}

		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
	}
	
}
